<template>
  <!-- 主页面左侧组件列表项 -->
  <div class="vy-theme-center">
    <div class="vy-wrapper">
      <div class="vy-box">
        <div class="vy-box-left">主题内容</div>
      </div>
    </div>
    <div class="vy-theme-container" :class="{ 'vy-draw-panel': isFlod }">
      <!-- <div class="vy-theme-container"> -->
      <template v-if="!currentView">
        <div class="default_box">
          <div class="default_img">
            <img src="../../images/nodata.png" />
          </div>
          <div class="default_btn">
            <a-button
              type="primary"
              shape="round"
              :disabled="!!!String(activedTab.id || '')"
              @click="click_show_cmp_modal"
              >设置内容</a-button
            >
          </div>
        </div>
      </template>
      <template v-else>
        <a-card :title="currentViewName" class="vy-theme-panel">
          <div slot="extra">
            <a-button
              type="link"
              icon="sync"
              @click="click_show_cmp_modal"
              style="color: #3D3D3D;padding:0;"
              >切换形式</a-button
            >
          </div>
          <component
            @work-rule-value="handleRuleValue"
            @card-rule-value="handleRuleValue"
            @exam-rule-value="handExamRuleValue"
            :is="currentView"
            :key="viewKey"
          ></component>
        </a-card>
        <div class="vy-float-btn" v-if="isFlod" @click="() => (isFlod = false)">
          <div
            style="position: absolute;bottom: 10px;left: 0;right: 0;cursor: pointer; padding:10px 0px;"
          >
            展开内容<a-icon type="caret-down" />
          </div>
        </div>
      </template>
    </div>
    <mu-flex
      class="theme-rule-btn"
      align-items="center"
      justify-content="center"
      @click="themeRule = true"
      v-if="
        themeRule === false &&
          moduleInfo &&
          (moduleItemType === 10 || moduleItemType === 11)
      "
    >
      <span>主题规则</span>
      <img src="https://image.xuexiwangzhe.com/Fuh7lg6f5NsQtf6WjBWBoMrX_ixG" />
    </mu-flex>
    <mu-flex
      class="theme-rule-btn"
      align-items="center"
      justify-content="center"
      @click="themeRuleExam = true"
      v-else-if="themeRule === false && moduleInfo && moduleItemType === 13"
    >
      <span>主题规则</span>
      <img src="https://image.xuexiwangzhe.com/Fuh7lg6f5NsQtf6WjBWBoMrX_ixG" />
    </mu-flex>
    <mu-drawer
      class="theme-rule-drawer"
      :z-depth="0"
      :open.sync="themeRuleExam"
      :docked="false"
      :right="true"
    >
      <mu-flex
        class="theme-rule-btn"
        align-items="center"
        justify-content="center"
        @click="themeRuleExam = false"
        style="position:relative;top:0;right:0;"
      >
        <span>主题规则</span>
        <img
          src="https://image.xuexiwangzhe.com/Fg2cxbfh7rBMp-Ipl-5TJeP9C9JX"
        />
      </mu-flex>
      <div
        style="width:256px;background-color:#fff;padding-top:47px;padding-left:20px;"
      >
        <div class="select-list-title">
          <span class="select-list-title-sign"></span>
          <span>显示风格</span>
        </div>
        <div style="margin-bottom:49px;">
          <mu-radio
            v-model="examRule.style"
            class="select-item"
            :value="1"
            label="一次性显示所有问题"
          ></mu-radio>
          <mu-radio
            class="select-item"
            :value="2"
            v-model="examRule.style"
            label="每页显示一道题目"
          ></mu-radio>
        </div>
        <div class="select-list-title">
          <span class="select-list-title-sign"></span>
          <span>功能设置</span>
        </div>
        <div style="margin-bottom:57px;">
          <mu-checkbox
            v-model="examRule.use"
            class="select-item"
            value="disorganize"
            label="打乱考题顺序"
          ></mu-checkbox>
          <mu-checkbox
            v-model="examRule.use"
            class="select-item"
            value="answerOrder"
            label="打乱答案顺序"
          ></mu-checkbox>
          <mu-checkbox
            v-model="examRule.use"
            class="select-item"
            value="showCorrent"
            label="提示答案"
          ></mu-checkbox>
          <mu-checkbox
            v-model="examRule.use"
            class="select-item"
            value="showScore"
            label="显示成绩"
          ></mu-checkbox>
          <mu-checkbox
            v-model="examRule.use"
            class="select-item"
            value="viewResult"
            label="允许查看结果"
          ></mu-checkbox>
          <mu-checkbox
            v-model="examRule.use"
            class="select-item"
            value="showAnalysis"
            label="允许查看解析"
          ></mu-checkbox>
        </div>
        <mu-button class="save-rule-btn" @click="saveExamRule">保存规则</mu-button>
      </div>
    </mu-drawer>
    <mu-drawer
      class="theme-rule-drawer"
      :z-depth="0"
      :open.sync="themeRule"
      :docked="false"
      :right="true"
    >
      <mu-flex
        class="theme-rule-btn"
        align-items="center"
        justify-content="center"
        @click="themeRule = false"
        style="position:relative;top:0;right:0;"
      >
        <span>主题规则</span>
        <img
          src="https://image.xuexiwangzhe.com/Fg2cxbfh7rBMp-Ipl-5TJeP9C9JX"
        />
      </mu-flex>
      <div
        style="width:256px;background-color:#fff;padding-top:20px;padding-left:20px;"
      >
        <div style="margin-bottom:20px;">
          <mu-radio
            v-model="ruleSelect"
            :class="[
              'select-item',
              ruleSelect === 0 ? 'select-item-actived' : '',
            ]"
            :value="0"
            label="公开"
          ></mu-radio>
          <mu-radio
            :class="[
              'select-item',
              ruleSelect === 1 ? 'select-item-actived' : '',
            ]"
            :value="1"
            v-model="ruleSelect"
            label="非公开"
          ></mu-radio>
          <mu-radio
            :class="[
              'select-item',
              ruleSelect === 2 ? 'select-item-actived' : '',
            ]"
            :value="2"
            v-model="ruleSelect"
            label="小组"
          ></mu-radio>
        </div>
        <mu-button class="save-rule-btn" @click="saveRule">保存规则</mu-button>
      </div>
    </mu-drawer>

    <vy-cmp-result-index ref="resultIndex"></vy-cmp-result-index>

    <!-- 设置内容 - 弹框选择 -->
    <a-modal
      title="选择形式"
      class="vy-modal"
      centered
      :closable="true"
      @cancel="click_set_close"
      :maskClosable="false"
      :width="820"
      v-model="modal2Visible"
    >
      <template slot="footer">
        <div class="vy-modal-footer">
          <a-button type="primary" @click="click_set_ok">选择</a-button>
        </div>
      </template>
      <div class="vy-modal-content">
        <vy-cmp-index ref="cmps" @vy_click="vy_cmp_click"></vy-cmp-index>
      </div>
    </a-modal>
  </div>
</template>

<script>
import VyCmpIndex from "../cmps/index.vue";
import VyCmpResultIndex from "./center/index.vue";
import { themeCovertType } from "../../../../../util/common.js";
export default {
  name: "vy-theme-center",
  data() {
    return {
      modal2Visible: false, // modal 框
      themeRule: false,
      themeRuleExam: false,
      viewFlag: null, // 临时视图标识
      currentView: null, // 组件视图组件
      currentViewName: "", // 组件视图名称
      temp_choosed: null, // 弹框中选中的组件
      activedTab: {}, // 左侧列表选中的tab
      isFlod: false, // 编辑区域是否折叠
      moduleInfo: {}, // 原有组件内容
      projectId: null, // 项目Id
      viewKey: new Date().getTime(), // 用于清除动态组件缓存
      ruleSelect: -1,
      examRule: {
        style: -1,
        use: [],
      },
    };
  },
  components: {
    [VyCmpIndex.name]: VyCmpIndex,
    [VyCmpResultIndex.name]: VyCmpResultIndex,
  },
  created() {
    this.projectId = this.$route.query.projectId;    
  },
  mounted() {
    this.$bus.on("activeLeftTab", (obj) => {
      this.activedTab = obj;
      // 查询内容组件列表
      this.$nextTick(() => {
        setTimeout(() => {
          this.queryModuleInfo();
          if (this.$refs["resultIndex"]) {
            this.$refs["resultIndex"].resetTabs();
            // 设置参数，后面子组件的导出结果会用到
            this.$refs["resultIndex"].leftActivedTab = this.activedTab;
            this.$refs["resultIndex"].projectId = this.projectId;
            this.$refs["resultIndex"].hasResults();            
          }
        }, 100);
      });
    });
  },
  methods: {
    // 查询内容组件列表
    queryModuleInfo(_type) {
      let params = {
        id: this.activedTab && this.activedTab.itemId, // 组件Id
        moduleId: this.activedTab && this.activedTab.id, // 主题Id
        moduleType: _type || (this.activedTab && this.activedTab.type), // 组件类型
        projectId: this.projectId, // 项目Id
      };      
      this.$axios.get("/subassembly/get", { params }).then((res) => {
        if (res.success) {
          this.moduleInfo = (res && res.subassemblyVo) || {};
          let cmp = window.getCmpType(this.moduleInfo.moduleType);
          // 读取自定义组件
          const requireComponents = this._getComponents();
          // 遍历出每个组件的路径
          requireComponents.keys().forEach((fileName) => {
            // 获取组件名称
            var reqComName = fileName.substring(
              fileName.lastIndexOf("/") + 1,
              fileName.lastIndexOf(".")
            );
            // 判断组件名称和当前flag值
            if (reqComName == cmp.cmpflag) {
              // 加载对应的组件实例
              const reqCom = requireComponents(fileName);
              this.viewKey = new Date().getTime();
              this.currentView = Object.assign({}, reqCom.default); // 设置动态组件实例
              let me = this; // 当前 center 组件对象
              this.setEditerContent(me.moduleInfo); // 兼容ckediter的绑定问题
              // 【注意事项⚠️】
              this.currentView.created = function() {
                this.projectId = me.projectId;
                // 传递左侧列表选中的tab信息到添加的子组件类型中
                this.themeTab = me.activedTab || {};
                // 传递当前已创建的组件内容到对应的动态组件中
                this.formData = Object.assign(this.formData, me.moduleInfo);
              };
              this.currentViewName = cmp.title; // 设置动态组件名称
            }
          });
        } else {
          this.viewFlag = null; // 临时视图标识
          this.currentView = null; // 组件视图组件
          this.currentViewName = ""; // 组件视图名称
          this.moduleInfo = {}; // 原有组件内容
          this.isFlod = false; // 编辑区域不折叠
          if (this.$refs["resultIndex"]) {
            this.$refs["resultIndex"].showResultList = false; // 不展示参与结果
          }
        }
      });
    },
    _getComponents() {
      // 读取自定义组件
      return require.context("../rightedit", false, /\.vue/);
    },
    vy_cmp_click(flag, item) {
      let cmpFileNames = [];
      // 读取自定义组件
      const requireComponents = this._getComponents();
      // 遍历出每个组件的路径
      requireComponents.keys().forEach((fileName) => {
        // 获取组件名称
        var reqComName = fileName.substring(
          fileName.lastIndexOf("/") + 1,
          fileName.lastIndexOf(".")
        );
        cmpFileNames.push(reqComName);
      });
      // 设置组件视图标记
      this.viewFlag = cmpFileNames.includes(flag) ? flag : null;
      this.temp_choosed = item; // 记录选中的组件信息
    },
    // 弹框 - 选择事件
    click_set_ok() {
      // 没有选中过页面组件
      if (!this.temp_choosed) {
        this.$message.error("请选择形式");
        return;
      }
      this.modal2Visible = false; // 隐藏弹框
      this.$refs["cmps"].resetActived(); // 重置弹框组件中选中状态
      if (!this.viewFlag) {
        this.$message.error("暂不支持该组件");
        return;
      }
      this.themeRule = false;
      // 读取自定义组件
      const requireComponents = this._getComponents();
      // 遍历出每个组件的路径
      requireComponents.keys().forEach((fileName) => {
        // 获取组件名称
        var reqComName = fileName.substring(
          fileName.lastIndexOf("/") + 1,
          fileName.lastIndexOf(".")
        );
        // 判断组件名称和当前flag值
        if (reqComName == this.viewFlag) {
          // 加载对应的组件实例
          const reqCom = requireComponents(fileName);
          this.currentView = reqCom.default; // 设置动态组件实例
          let me = this; // 当前 center 组件对象
          me.moduleInfo = {}; // 清空第一次查询出来的原有组件内容
          this.setEditerContent(me.moduleInfo); // 兼容ckediter的绑定问题
          // 【注意事项⚠️】
          this.currentView.created = function() {
            this.projectId = me.projectId;
            // 传递左侧列表选中的tab信息到添加的子组件类型中
            this.themeTab = me.activedTab || {};
            // 传递当前已创建的组件内容到对应的动态组件中
            Object.assign(this.formData, me.moduleInfo);
          };
          this.currentViewName = this.temp_choosed && this.temp_choosed.name; // 设置动态组件名称
        }
      });
    },
    // 弹框 - 关闭事件 - Modal 完全关闭后的回调
    click_set_close() {
      this.$refs["cmps"].resetActived(); // 重置弹框组件中选中状态
      // 重置选中的组件信息
      this.temp_choosed = null;
      // 重置组件视图标记
      this.viewFlag = null;
    },
    // 兼容处理富文本值异常报错问题
    setEditerContent(obj) {
      obj.content = obj.content || "";
      obj.introduce = obj.introduce || "";
      obj.testIntroduce = obj.testIntroduce || "";
    },
    // 显示选择形式弹框
    click_show_cmp_modal() {
      if (!this.activedTab.id) {
        this.$message.error("请选择左侧主题");
        return;
      }
      this.modal2Visible = true;
      this.isFlod = false;
    },
    saveRule() {
      if (this.ruleSelect < 0) {
        this.$toast.error("请先选择规则");
        return;
      }
      const params = {
        moduleType: this.moduleInfo.moduleType,
        projectId: this.moduleInfo.projectId,
        moduleId: this.moduleInfo.moduleId, // 主题Id
        id: this.moduleInfo.id || "",
        showContent: this.ruleSelect,
      };
      this.$axios.post("/subassembly/saveModuleRule", params).then((res) => {
        if (res.success) {
          this.$toast.success("规则更新成功");
          this.themeRule = false;
        } else {
          this.$toast.error(res.msg);
        }
      });
    },
    saveExamRule() {
      if (this.examRule.style <= 0) {
        this.$toast.error("请先选择显示风格");
        return;
      }
      let useResult = {
        disorganize: 0,
        answerOrder: 0,
        showCorrent: 0,
        showScore: 0,
        viewResult: 0,
        showAnalysis: 0,
      };
      this.examRule.use.forEach((item) => {
        useResult[item] = 1;
      });

      const params = {
        moduleType: this.moduleInfo.moduleType,
        projectId: this.moduleInfo.projectId,
        moduleId: this.moduleInfo.moduleId, // 主题Id
        id: this.moduleInfo.id || "",
        showQuestion: this.examRule.style,
        ...useResult,
      };

      this.$axios.post("/subassembly/saveModuleRule", params).then((res) => {
        if (res.success) {
          this.$toast.success("规则更新成功");
          this.themeRuleExam = false;
        } else {
          this.$toast.error(res.msg);
        }
      });
    },
    handleRuleValue(value) {
      this.ruleSelect = value;
    },
    handExamRuleValue(value) {      
      this.examRule = value;      
    },
  },
  computed: {
    moduleItemType() {
      return themeCovertType(this.moduleInfo.moduleType);
    },
  },
};
</script>

<style lang="scss">
.vy-theme-center {
  position: relative;
  width: 100%;
  min-height: 100%;

  .theme-rule-btn {
    position: absolute;
    top: 10px;
    right: -100px;
    border-top-left-radius: 23px;
    border-bottom-left-radius: 23px;
    box-shadow: rgba(197, 197, 197, 0.2) 2px 5px 7px 0px;
    font-size: 18px;
    background-color: rgb(255, 255, 255);
    height: 47px;
    width: 135px;
    cursor: pointer;

    > span {
      margin-right: 6px;
    }

    > img {
      width: 16px;
    }
  }

  .theme-rule-drawer {
    top: 70px;
    display: flex;
    width: auto;
    background-color: transparent;
    height: calc(100% - 70px);

    .select-list-title {
      display: flex;
      align-items: center;
      color: #242323;
      margin-bottom: 12px;
    }

    .select-list-title-sign {
      width: 3px;
      height: 17px;
      background-color: #3366ff;
      margin-right: 12px;
    }

    .select-item {
      display: block;
      font-size: 14px;
      color: #bab7b7;
      margin-bottom: 10px;
      &:last-child {
        margin-bottom: 0;
      }
      .mu-radio-wrapper {
        justify-content: flex-start;
      }
      .mu-checkbox-wrapper {
        justify-content: flex-start;
      }

      .mu-radio-label,
      .mu-checkbox-label {
        color: #bab7b7;
        font-size: 14px;
      }
    }

    .mu-radio-checked {
      color: #3366ff;
      .mu-radio-label {
        color: #444040;
      }
    }

    .mu-checkbox-checked {
      color: #3366ff;
      .mu-checkbox-label {
        color: #444040;
      }
    }

    .select-item-actived {
      color: #3366ff;
      .mu-radio-label,
      .mu-checkbox-label {
        color: #444040;
      }
    }

    .save-rule-btn {
      width: 200px;
      background-color: #3366ff;
      color: #fff;
      box-shadow: -2px 2px 8px 1px rgba(218, 218, 218, 0.36);
      border-radius: 8px;
    }
  }
  .vy-wrapper {
    padding: 30px 0 15px 0;
  }
  .vy-result-list-wrapper {
    padding: 50px 0 15px 0;
  }
  .vy-box {
    display: flex;
    align-items: center;
    .vy-box-left {
      width: 100px;
      font-size: 18px;
      font-weight: 500;
      color: rgba(0, 0, 0, 1);
    }
    .vy-box-center {
      flex: 1;
    }
    .vy-box-right {
      width: 50px;
      font-weight: 400;
      font-size: 13px;
      text-align: right;
      color: rgba(51, 102, 255, 1);
    }
  }
  .vy-theme-container {
    // padding: 0 15px;
    width: 100%;
    position: relative;
    background: #ffffff;
    &.vy-draw-panel {
      height: 150px;
      overflow: hidden;
    }
    .default_box {
      top: 50%;
      left: 50%;
      text-align: center;
      padding: 50px 0;
      .default_img {
        img {
          width: calc(320px * 2 / 3);
          height: calc(288px * 2 / 3);
          display: block;
          margin: 0 auto;
        }
      }
      .default_btn {
        padding: 50px;
        .ant-btn {
          padding: 10px 50px;
          height: auto;
          &.ant-btn-primary {
            background: rgba(51, 102, 255, 1);
            &:hover {
              background: rgba(51, 102, 255, 0.8);
            }
            &[disabled] {
              background: #f5f5f5;
              &:hover {
                background: #f5f5f5;
              }
            }
          }
        }
      }
    }
    .vy-theme-panel {
      border: 0;
      padding: 0 15px;
      .ant-card-head {
        border-bottom: none;
        padding: 0 20px;
        .ant-card-head-wrapper {
          .ant-card-head-title {
            font-size: 22px;
            font-weight: 500;
            color: rgba(0, 0, 0, 1);
          }
        }
      }
      .ant-card-body {
        padding: 20px;
      }
    }
    .vy-float-btn {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      top: 0;
      text-align: center;
      background: linear-gradient(
        180deg,
        rgba(255, 255, 255, 0.5) 0%,
        rgba(255, 255, 255, 0.84) 48%,
        rgba(255, 255, 255, 1) 100%
      );
      border-radius: 0px 0px 8px 8px;
      z-index: 11;
      color: #3366ff;
    }
  }
}
.vy-modal {
  .ant-modal-header {
    text-align: center;
  }
  .vy-modal-footer {
    text-align: center;
    .ant-btn {
      height: auto;
      font-size: 16px;
      padding: 10px 100px;
      &.ant-btn-primary {
        background: rgba(51, 102, 255, 1);
        &:hover {
          background: rgba(51, 102, 255, 0.8);
        }
        &[disabled] {
          background: #f5f5f5;
          &:hover {
            background: #f5f5f5;
          }
        }
      }
    }
  }
}
</style>
